# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import email.mime.multipart
import email.mime.text
import os
import smtplib
import sys

# How much of the logfile to send in the email (calculated from the end).
MAX_BYTES_TO_SEND = 50000
MAX_LINES_TO_SEND = 500
SUMMARY_LINES_TO_SEND = 20

def ParseMailConfig(json_config):
  local_scope = {}
  global_scope = {}
  exec(json_config, global_scope, local_scope)
  return local_scope['mail_config']

def SendMail(config, subject, body, log_attachment=None):
  message = email.mime.multipart.MIMEMultipart()
  message['From'] = 'DevToolsFE Uploader <%s>' % config['FROM_ADDRESS']
  message['To'] = config['TO_ADDRESS']
  message['Subject'] = subject
  message.attach(email.mime.text.MIMEText(body))
  if log_attachment:
    attachment = email.mime.text.MIMEText(log_attachment)
    attachment.add_header('Content-Disposition', 'attachment',
                          filename='log.txt')
    message.attach(attachment)

  server = smtplib.SMTP('smtp.gmail.com:587')
  server.starttls()
  server.login(config['FROM_ADDRESS'], config['PASSWORD'])
  server.sendmail(config['FROM_ADDRESS'], config['TO_ADDRESS'], message.as_string())
  server.quit()

def SendErrorMail(config, reason, repeat, logpath):
  intro = ("The uploader encountered an error (during step '%s').\n"
           "This has happened %d time%s in a row.\n\n"
           "Last %d lines of log (more of the log is attached):\n\n"
           ) % (reason, repeat, 's' if repeat != 1 else '',
                SUMMARY_LINES_TO_SEND)

  with open(logpath, 'rb') as log:
    log.seek(0, os.SEEK_END)
    if log.tell() < MAX_BYTES_TO_SEND:
      log.seek(0, os.SEEK_SET)
    else:
      log.seek(-MAX_BYTES_TO_SEND, os.SEEK_END)
    lines = log.readlines()
    lines = lines[-MAX_LINES_TO_SEND:]

  summary = ''.join(lines[-SUMMARY_LINES_TO_SEND:])
  full_log = ''.join(lines)

  SendMail(config, 'Uploader failure: %s' % reason, intro + summary, full_log)


def SendAllClearMail(config):
  SendMail(config,
           'Uploader all clear',
           'The uploader cycled successfully; previous errors are fixed.')
